package com.duowan.cms.common.util;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * 文件读写操作工具类
 *
 * <br>==========================
 * <br> 公司：欢聚时代
 * <br> 开发：qiusidi@yy.com
 * <br> 版本：1.0
 * <br> 创建时间：2012-10-11
 * <br>==========================
 */
public abstract class FileUtil {

    private static final Log LOG = LogFactory.getLog(FileUtil.class);

    private static final String DEF_ENCODEING = "UTF-8";

    public static final String SUFFIX = ".log"; // 用于日志文件的后缀

    // 定义文件分隔符，方便统一修改
    public static final String FILE_SEPARATOR = "/";

    /**
     * 统一文件目录分隔符
     */
    public static String getFilePath(String path) {
        if (StringUtil.isEmpty(path))
            return "";
        return path.replace("/", System.getProperty("file.separator")).replace("\\", System.getProperty("file.separator"));// 统一文件目录分隔符
    }

    /**
     * 根据文件名字判断文件是否图片
     * @param fileName
     * @return
     */
    public static boolean isPicFormat(String fileName) {
        String reg = "(?i).*\\.(jpg)|(jpeg)|(png)|(gif)|(bmp)|(ico)";
        Pattern pattern = Pattern.compile(reg);
        Matcher matcher = pattern.matcher(fileName);
        if (matcher.find()) {
            return true;
        }
        return false;
    }

    /**
     * 读取指定文件的文本内容 
     * @param filepath 文件的路劲
     * @param encode 文件编码
     * @return
     */
    public static String readFile(String filepath, String encode) {
        File ft = new File(filepath);
        StringBuffer sb = new StringBuffer();
        try {
            InputStream is = new FileInputStream(ft);
            BufferedReader in = new BufferedReader(new InputStreamReader(is, encode));
            String aline = "";
            while (null != (aline = in.readLine())) {
                sb.append(aline + "\n");
            }
            is.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return sb.toString();
    }

    public static String readFile(String filepath) {
        return readFile(filepath, DEF_ENCODEING);
    }

    public static String getRandomFileNameByFileItem(FileItem item) {
        String fileName = FileUtil.getFileNameByFileItem(item);
        String fileSuffix = "";
        if (fileName.indexOf(".") > -1) {
            fileSuffix = fileName.substring(fileName.lastIndexOf(".") + 1);
        }

        return new Date().getTime() + "." + fileSuffix;
    }

    public static String getFileNameByFileItem(FileItem item) {
        String itemName = item.getName().replace("\\", FileUtil.FILE_SEPARATOR);
        if (itemName.indexOf(":") > -1) {// windows可以得到文件名，而linux下得到的却是完整路径
            itemName = itemName.substring(itemName.lastIndexOf("/"));
        }
        if (itemName.indexOf("&") > -1) {
            itemName = itemName.replace("&", "-");
        }
        return itemName;
    }

    /**
     * 把字符串写入文本文件
     * @param filename 文件的路径
     * @param content 字符串
     * @param encode 字符编码
     * @param mkdir  是否自动创建目录
    * @throws IOException 
     */
    public static void write(String filename, String content, String encode, boolean mkdir) throws IOException {
        FileOutputStream os = null;
        BufferedWriter out = null;
        try {
            os = new FileOutputStream(filename, false);
            out = new BufferedWriter(new OutputStreamWriter(os, encode), 64 * 1024);
            out.write(content);
            out.close();
            os.close();
        } catch (FileNotFoundException e1) {
            String path = filename.substring(0, filename.lastIndexOf("/"));
            LOG.info("文件目录" + path + "不存在。");
            if (mkdir) {
                boolean success = mkdir(path);
                if (success) {
                    LOG.info("文件目录" + path + "创建成功。");
                    write(filename, content, encode, true);
                } else {
                    LOG.info("文件目录" + path + "创建失败。");
                    throw e1;
                }
            } else {
                throw e1;
            }
        } finally {
            try {
                out.close();
                os.close();
            } catch (Exception e) {
                e.printStackTrace();
            }

        }
    }

    public static void write(String filename, String content) throws IOException {
        write(filename, content, true);
    }

    public static void write(String filename, String content, boolean mkdir) throws IOException {
        write(filename, content, "UTF-8", mkdir);
    }

    public static boolean mkdir(String path) {
        File ft = new File(path);
        if (!ft.exists()) {
            return ft.mkdirs();
        }
        return true;
    }

    /**
     * 根据文件名获取指定的文件
     * @param fileName 文件名
     * @param isCreate 如果文件不存在，是否需要创建
     * @return
     */
    public static File loadFile(String fileName, boolean isCreate) throws IOException {
        File file = new File(fileName);
        if (file.exists())
            return file;

        if (!isCreate)
            return null;

        File parentFile = file.getParentFile();
        if (!parentFile.exists() && parentFile.getPath() != null && !"".equals(parentFile.getPath()))
            if (!parentFile.mkdirs())
                return null;

        if (file.createNewFile())
            return file;

        return null;
    }

    /**
     * 路径指向的是否是一个文件件
     * 
     * @param path
     * @return
     */
    public static boolean mkDirs(String path) {
        File file = new File(path);
        if (!file.isDirectory()) {
            return file.mkdirs();
        }
        return file.isDirectory();
    }

    /**
     * 删除指定的文件
     * @param fileName
     * @return
     */
    public static boolean delete(String filePath) {
        File file = new File(filePath);
        if (file.isFile() && file.exists()) {
            return file.delete();
        } else {
            return false;
        }
    }

    /**
     * 修改文件名字
     * @param filename
     * @param dest
     * @return
     */
    public static boolean rename(String filename, String dest) {
        File file = new File(filename);
        if (!file.exists()) {
            return false;
        }
        File file1 = new File(dest);
        if (file1.exists()) {
            return false;
        }
        return file.renameTo(file1);
    }

    /**
     * 文件拷贝
     * @param source
     * @param target
     * @return
     */
    public static int copyFile(String source, String target) {
        int bytesum = 0;
        int byteread = 0;
        File oldfile = new File(source);
        if (!oldfile.exists()) { // 文件存在时
            return -1;
        }
        try {
            InputStream inStream = new FileInputStream(source); // 读入原文件
            FileOutputStream fs = new FileOutputStream(target);
            byte[] buffer = new byte[1024 * 5];
            while ((byteread = inStream.read(buffer)) != -1) {
                bytesum += byteread; // 字节数 文件大小
                // System.out.println(bytesum);
                fs.write(buffer, 0, byteread);
            }
            inStream.close();
        } catch (java.io.IOException e) {
            e.printStackTrace();
            return -2;
        }
        return 1;
    }

    /**
     * 删除文件夹里面的所有文件
     * @param path String 文件夹路径
     */
    public static void deleleAllFile(String path) {
        File file = new File(path);
        if (!file.exists()) {
            return;
        }
        if (!file.isDirectory()) {
            return;
        }
        String[] tempList = file.list();
        File temp = null;
        for (int i = 0; i < tempList.length; i++) {
            if (path.endsWith(File.separator)) {
                temp = new File(path + tempList[i]);
            } else {
                temp = new File(path + File.separator + tempList[i]);
            }
            if (temp.isFile()) {
                temp.delete();
            }
            if (temp.isDirectory()) {
                deleleAllFile(path + "/" + tempList[i]); // 先删除文件夹里面的文件
                deleleFolder(path + "/" + tempList[i]); // 再删除空文件夹
            }
        }
    }

    /**
     * 删除文件夹
     * @param folderPath
     */
    public static void deleleFolder(String folderPath) {
        try {
            deleleAllFile(folderPath); // 删除完里面所有内容
            String filePath = folderPath;
            filePath = filePath.toString();
            File myFilePath = new File(filePath);
            myFilePath.delete(); // 删除空文件夹
        } catch (Exception e) {
            System.out.println("删除文件夹操作出错");
            e.printStackTrace();

        }

    }

    /**
     * 文件是否存在
     * @param path
     * @return
     */
    public static boolean isFileExists(String path) {
        if (StringUtil.isEmpty(path)) {
            return false;
        }
        return new File(path).exists();
    }

    /**
     * 是否是文本文件名称
     * @param filename
     * @return
     */
    public static boolean isTextFilename(String filename) {
        if (filename == null)
            return false;
        filename = filename.toLowerCase();
        return filename.endsWith("txt") || filename.endsWith("text") || filename.endsWith("log");
    }

    /**
     * 是否是图片文件名称
     * @param filename
     * @return
     */
    public static boolean isPicFilename(String filename) {
        if (filename == null)
            return false;
        filename = filename.toLowerCase();
        return filename.endsWith("png") || filename.endsWith("jpg") || filename.endsWith("gif") || filename.endsWith("jpeg");
    }

}
